package cn.easier.activity.console.controller;

import cn.easier.activity.console.configration.ActivityConsoleConfiguration;
import cn.easier.activity.console.service.ActivityCouponCodeService;
import cn.easier.activity.console.service.ActivityInfoService;
import cn.easier.activity.console.utils.FileUtil;
import cn.easier.activity.console.utils.ReadExcelUtil;
import cn.easier.activity.web.entity.ActivityCouponCode;
import cn.easier.activity.web.entity.ActivityInfo;
import cn.easier.activity.web.entity.CouponType;
import cn.easier.club.base.dto.ResultInfo;
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 券码表
 */
@Controller
@RequestMapping("/activity/info/prize/couponCode")
public class ActivityCouponCodeController extends BaseController{

    Logger logger = LoggerFactory.getLogger(ActivityCouponCodeController.class);
    @Autowired
    ActivityCouponCodeService activityCouponCodeServices;

    @Autowired
    ActivityInfoService activityInfoService;

    @Autowired
    ActivityConsoleConfiguration activityConsoleConfiguration;

    /**
     * 查找指定活动奖品券码列表
     *
     * @return
     */
    @GetMapping
    @ResponseBody
    public List<ActivityCouponCode> findList(@RequestParam(value = "activityPrizeId") Integer activityPrizeId) {
        if (activityPrizeId == null || activityPrizeId < 1) {
            return null;
        }
        List<ActivityCouponCode> activityCouponCodes = null;
        String user = this.getPrincipal().getUsername();
        String authoritiesStr = this.getPrincipal().getAuthoritiesStr();
        ActivityInfo activityInfo = null;
        try {
            if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
                activityInfo = activityInfoService.findInfo(activityPrizeId);
            } else {
                activityInfo = activityInfoService.findByInfo(user, activityPrizeId);
                if (!user.equals(activityInfo.getCreateBy())) {
                    return null;
                }
            }
            //验证activityPrizeId
            if (activityInfo == null) {
                logger.info("活动奖品券码列表失败,activityPrizeId验证失败：id =>{}", activityPrizeId);
            }
            logger.info("获取奖品券码列表验证通过，activityPrizeId：=>{}", activityPrizeId);
            //获取券码列表
//            activityCouponCodes = activityCouponCodeServices.findList(activityPrizeId);
            logger.info("获取奖品券码列表，activityPrizeId：=>{}, activityCouponCodes =>{}", activityPrizeId, activityCouponCodes);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取奖品券码列表失败，activityPrizeId：=>{}", activityPrizeId);
        }
        return activityCouponCodes;
    }

    /**
     * 查找奖品券码使用情况
     * TODO 查找某活动的券码奖品使用情况，还是所有券码类型奖品的使用情况。
     *
     * @return
     */
    @GetMapping("detail")
    @ResponseBody
    public ResultInfo couponCodeDetail(@RequestParam(value = "activityPrizeId") Integer activityPrizeId) {
        if (activityPrizeId == null || activityPrizeId < 1) {
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "查找奖品券码使用情况失败,奖品编号有误", null);
        }
        String user = this.getPrincipal().getUsername();
        String authoritiesStr = this.getPrincipal().getAuthoritiesStr();
        ResultInfo resultInfo = null;
        try {
            //验证activityPrizeId
            ActivityInfo activityInfo = activityInfoService.findInfo(activityPrizeId);
            //如果没有该活动或者该活动不属于当前用户管理，返回失败。
            if (activityInfo == null || (!user.equals(activityInfo.getCreateBy()))) {
                logger.info("查找奖品券码详情失败,activityPrizeId验证失败：=>{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "查找奖品券码详情失败,奖品编号有误", null);
            }
            //暂时查询某券码奖品的券码使用情况。 TODO 暂时保留此接口，以后修改为平台券码奖品使用情况。
//            int trueFlag = activityCouponCodeServices.countByAvailable(activityPrizeId, true);
//            int falseFlag = activityCouponCodeServices.countByAvailable(activityPrizeId, false);
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("trueFlag", trueFlag);
//            map.put("falseFlag", falseFlag);
//            new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "查找奖品券码详情成功", map);
            logger.info("查找奖品券码详情成功，activityPrizeId：=>{}", activityPrizeId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("查找奖品券码详情异常，activityPrizeId：=>{}", activityPrizeId);
        }
        return resultInfo;
    }

    /**
     * 查找指定活动奖品券码
     *
     * @return
     */
    @GetMapping("/id/{id}")
    @ResponseBody
    public ActivityCouponCode findOne(@PathVariable Integer id) {
        if (id == null || id < 1) {
            return null;
        }
        String user = this.getPrincipal().getUsername();
        String authoritiesStr = this.getPrincipal().getAuthoritiesStr();
        ActivityCouponCode activityCouponCode = null;
        try {
            if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
                activityCouponCode = activityCouponCodeServices.findOne(id);
            } else {
                activityCouponCode = activityCouponCodeServices.findByOne(user, id);
                if (!user.equals(activityCouponCode.getUser())) {
                    logger.info("获取奖品券码异常, 用户不对称。 =>{}", user);
                    return null;
                }
            }
            if (activityCouponCode == null) {
                logger.info("获取奖品券码为null,id =>{}", id);
            }
            logger.info("获取奖品券码, activityCouponCode =>{}", activityCouponCode);
        } catch (Exception e) {
            logger.info("获取奖品券码异常, id =>{}", id);
        }
        return activityCouponCode;
    }

//    /**
//     * 创建活动券码
//     *
//     * @return
//     */
//    @PostMapping
//    @ResponseBody
//    public ResultInfo create(ActivityCouponCode activityCouponCode) {
//        ResultInfo resultInfo = null;
//        String user = SUPERUSER;
//        try {
//            //验证activityPrizeId
//            Integer activityPrizeId = activityCouponCode.getActivityPrizeId();
//            if (activityPrizeId == null || activityPrizeId < 1) {
//                resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "奖品券码必须要有奖品编号", null);
//            }
//
//            ActivityInfo activityInfo = activityInfoService.findInfo(activityPrizeId);
//            if (activityInfo == null) {
//                logger.info("创建奖品券码失败,activityPrizeId验证失败：id =>{}", activityPrizeId);
//            }
//            if (!user.equals(activityInfo.getCreateBy())) {
//                resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "用户信息有误", null);
//            }
//            logger.info("创建奖品券码验证通过，activityPrizeId：=>{}", activityPrizeId);
//            activityCouponCode.setUser(user);
//            activityCouponCode.setAvailable(true);
//            ActivityCouponCode returnActivityCouponCode = activityCouponCodeServices.save(activityCouponCode);
//            logger.info("创建活动奖品券码成功：=>{}", returnActivityCouponCode);
//            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", returnActivityCouponCode);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error("创建活动奖品券码失败");
//            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "创建活动奖品券码异常", null);
//        }
//        return resultInfo;
//    }

    /**
     * 批量导入券码
     *
     * @return
     */
    @PostMapping("/batch-import-excel-file")
    @ResponseBody
    public ResultInfo batchImport(ActivityCouponCode activityCouponCode, @RequestParam(value = "couponCodeExcelFile") MultipartFile couponCodeExcelFile) {
        ResultInfo resultInfo = null;
        //批量导入券码步骤：1、信息验证 2、上传文件 3、数据解析 4、券码批量添加
        String user = getPrincipal().getUsername();
        String authoritiesStr = getPrincipal().getAuthoritiesStr();
        try {
            //验证activityPrizeId
            Integer activityPrizeId = activityCouponCode.getActivityPrizeId();
            if (activityPrizeId == null || activityPrizeId < 1) {
                logger.info("批量导入奖品券码失败,activityPrizeId不合法, ->{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "批量导入奖品券码失败，奖品券码必须要有奖品编号", null);
            }
            if (couponCodeExcelFile == null || Strings.isNullOrEmpty(couponCodeExcelFile.getOriginalFilename())) {
                logger.info("批量导入失败，没有找到文件。activityPrizeId =>{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "没有找到文件，请上传文件", null);

            }
            ActivityInfo activityInfo = activityInfoService.findInfo(activityPrizeId);
            if (activityInfo == null) {
                logger.info("批量导入奖品券码失败,activityPrizeId验证失败：id =>{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "批量导入奖品券码失败,activityPrizeId验证失败：id =>{}", activityPrizeId);
            }
            if (authoritiesStr.equals("ROLE_USER_SELF")) {
                if (!user.equals(activityInfo.getCreateBy())) {
                    logger.info("批量导入奖品券码失败,用户无权添加奖品券码,user =>{}", user);
                    return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "批量导入奖品券码失败,用户无权添加奖品券码", null);
                }
            }
            String fileName = couponCodeExcelFile.getOriginalFilename();
            //验证图片文件格式
            boolean formatFlag = FileUtil.fileFormatVerification(fileName, FileUtil.EXCEL_FORMAT);
            if (!formatFlag) {
                logger.info("批量导入失败，文件格式不合法，activityPrizeId：=>{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "请选择格式为 *.xls,*.xlsx 的文件", fileName);
            }
            logger.info("批量导入奖品券码验证通过，activityPrizeId：=>{}", activityPrizeId);

            //上传文件
            String excelFilePathConfig = activityConsoleConfiguration.activityCouponCodeExcelFilePath + activityPrizeId + "/";
            String filePath = uploadFile(couponCodeExcelFile, excelFilePathConfig, "couponCode_excel_");

            //如果文件路径不存在，返回
            if (Strings.isNullOrEmpty(filePath)) {
                logger.info("批量导入失败，上传文件失败。activityPrizeId =>{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "没有找到文件，上传文件失败", null);
            }

            //解析数据
            File excelFile = new File(filePath);
            List<List<String>> dataList = ReadExcelUtil.readExcel(excelFile);
            if (dataList == null || dataList.size() < 1 || dataList.get(0) == null || dataList.get(0).size() < 1) {
                logger.info("文件解析失败,请检查文件内容格式。activityPrizeId =>{}", activityPrizeId);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "文件解析失败,请检查文件内容格式", null);
            }

            //组织数据
            List<ActivityCouponCode> activityCouponCodeList = new ArrayList<ActivityCouponCode>();
            String timeStamp = String.valueOf(System.currentTimeMillis());
            for (List<String> row : dataList) {
                //创建券码
                ActivityCouponCode activityCouponCodeData = new ActivityCouponCode();
                activityCouponCodeData.setUser(user);
                activityCouponCodeData.setAvailable(true);
                activityCouponCodeData.setActivityPrizeId(activityCouponCode.getActivityPrizeId());
                activityCouponCodeData.setCouponType(activityCouponCode.getCouponType());
                activityCouponCodeData.setRemarks(activityCouponCode.getRemarks());
                //记录导入批次
                activityCouponCodeData.setName(timeStamp);
                if (CouponType.KEY.equals(activityCouponCode.getCouponType())) {
                    //“卡密”类型
                    if (StringUtils.isBlank(row.get(0))) {
                        logger.info("券码批量录入，数据不能为空");
                        throw new Exception("券码批量录入，数据不能为空");
                    }
                    activityCouponCodeData.setCode(row.get(0));
                } else if (CouponType.CODE_AND_KEY.equals(activityCouponCode.getCouponType())) {
                    //“卡号卡密”类型
                    if (StringUtils.isBlank(row.get(0)) || StringUtils.isBlank(row.get(1))) {
                        logger.info("券码批量录入，数据不能为空");
                        throw new Exception("券码批量录入，数据不能为空");
                    }
                    activityCouponCodeData.setCode(row.get(0));
                    activityCouponCodeData.setSecretKey(row.get(1));
                } else {
                    logger.info("无效的券码类型：=>{}", activityCouponCode.getCouponType());
                    break;
                }
                //添加券码
                activityCouponCodeList.add(activityCouponCodeData);
            }

            if (activityCouponCodeList.size() < 1) {
                logger.info("文件导入失败,没有数据或券码类型无效。activityCouponCode =>{}", activityCouponCode);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "文件导入失败,没有数据或券码类型无效", null);
            }
            //批量导入数据到数据库
            logger.info("券码读取完成，批量导入奖品券码");
            int importSize = activityCouponCodeServices.saveList(activityCouponCodeList).size();
            logger.info("批量导入奖品券码成功，导入：=>{}条数据", importSize);
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", importSize);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("批量导入券码,执行异常");
            resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "批量导入券码,执行异常", null);
        }
        return resultInfo;
    }

    /**
     * 获取积分墙商品列表
     *
     * @return
     */
    @GetMapping("/find-couponType-all")
    @ResponseBody
    public List findCouponTypeAll() {
        List couponTypeList = new ArrayList();
        CouponType[] couponTypes = CouponType.values();
        for (CouponType couponType : couponTypes) {
            Map map = new HashMap<String, Object>();
            map.put("name", couponType.getTypeName());
            map.put("identifier", couponType.getUniqueIdentifier());
            map.put("type", couponType);
            couponTypeList.add(map);
        }
        return couponTypeList;
    }

    /**
     * 查找指定活动奖品券码
     *
     * @return
     */
    @DeleteMapping("/id/{id}")
    @ResponseBody
    public Map<String, String> delete(@PathVariable Integer id) {
        //todo 需要添加验证
        Boolean deleteFlag = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            String user = getPrincipal().getUsername();
            String authoritiesStr = getPrincipal().getAuthoritiesStr();
            if (authoritiesStr.equals("ROLE_USER_SUPERADMIN") || authoritiesStr.equals("ROLE_USER_ADMIN")) {
                deleteFlag = activityCouponCodeServices.deleteByAdmin(id);
            } else {
                deleteFlag = activityCouponCodeServices.delete(id, user);
            }
            map.put("deleteFlag", deleteFlag ? "true" : "false");
            logger.info("删除奖品券码： id =>{}，flag =>{}", id, deleteFlag ? "SUCCESS" : "No Change");
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("删除奖品券码异常： id =>{}", id);
        }
        return map;
    }


    /**
     * 上传文件
     *
     * @return
     */
    private String uploadFile(MultipartFile excelFile, String prizePath, String fileNamePrefix) {
        //根路径
        String realPath = activityConsoleConfiguration.realPath;
        //文件路径
        String path = (realPath + prizePath).replace("/", File.separator);
        String imageFileName = FileUtil.doFile(excelFile, path, fileNamePrefix);
        //静态资源映射 + 文件地址 + 上传文件名称
        return path + imageFileName;
    }

}
